<template>
  <div class="flex-v flex" style="height: 100%">
    <div @click="goBack" class="flexBack">
      <img src="../../assets/image/zxl/fanhui.png" style="width: 8px; height: 12px; margin-right: 4px" />
      <span>返回</span>
    </div>

    <div class="infoBox">
      <div class="bottomBox">
        <div class="flex width100 borderbottomea paddingbottom20 box-align-center">
          <div class="zi1 flex">发起签署</div>
        </div>
        <div class="flex box-align-center mt20">
          <img src="@/assets/image/cf/img29.png" alt="" />
          <div class="zi2">参与人</div>
        </div>

        <div>
          <el-button type="primary" size="mini" color="#01509f" style="font-size: 15px" icon="Plus" @click="add" class="mt20">添加参与人</el-button>
          <el-button
            v-if="formadd.typename == '规章制度签署' || formadd.typename == '自定义签署'"
            type="primary"
            size="mini"
            color="#01509f"
            style="font-size: 15px"
            @click="showDialog1 = true"
            class="mt20"
          >
            批量导入
          </el-button>
          <el-button v-if="formadd.typename == '自定义签署'" type="primary" size="mini" color="#01509f" style="font-size: 15px" @click="addcompany" class="mt20">添加企业</el-button>
        </div>

        <el-table
          :data="list"
          border
          class="mt20"
          v-loading="loading"
          element-loading-background="rgba(0, 0, 0, 0.5)"
          empty-text="暂无数据"
          element-loading-text="加载中..."
          header-row-class-name="table-header"
        >
          <el-table-column label="任务主题" align="center" prop="main_name" v-if="formadd.typenamename != '规章制度签署'" />
          <el-table-column label="经办人证号" align="center" v-if="formadd.typenamename != '规章制度签署'">
            <template #default="{ row, $index }">
              <div v-if="row.join_type == 2">
                {{ row.join_name + +row.join_phone }}
              </div>
              <div v-else class="flex">
                <el-input v-model="row.join_name" placeholder="员工姓名"></el-input>
                <el-input v-model="row.join_phone" class="ml10 mr10" placeholder="手机号码"></el-input>
                <el-button type="primary" size="mini" color="#01509f" class="ml10" style="font-size: 15px" @click="addradio($index)">导入员工</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="员工姓名" align="center" v-if="formadd.typenamename == '规章制度签署'">
            <template #default="{ row, $index }">
              <div class="flex justify-content-center">
                <el-input v-model="row.join_name" placeholder="员工姓名" style="width: 45%"  class="mr10"></el-input>

                <el-button type="primary" size="mini" color="#01509f" class="ml10" style="font-size: 15px" @click="addradio($index)">导入员工</el-button>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="手机号码" align="center" v-if="formadd.typenamename == '规章制度签署'">
            <template #default="scope">
              <el-input v-model="scope.row.join_phone" class="ml10" placeholder="手机号码" style="width: 45%"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="签署要求" align="center" prop="yaoqiu" width="200" />
          <el-table-column label="操作" align="center" width="180">
            <template #default="scope">
              <el-button v-if="scope.row.join_type == 1" style="font-size: 16px; color: #ff4345" text icon="Delete" @click="deleteItem(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="flex box-align-center mt20">
          <img src="@/assets/image/cf/img28.png" alt="" />
          <div class="zi2">合同基本信息</div>
        </div>

        <div class="mt20 flex flex-v">
          <el-form ref="ruleFormRef" label-position="right" label-width="140px" :model="formadd" :rules="rules" class="form-inline">
            <div class="flex flex-v" style="width: 40%">
              <el-form-item class="" label="选择文件:" prop="filelist">
                <el-upload
                  class="avatar-uploader"
                  ref="uploadRef"
                  name="file"
                  :limit="1"
                  drag
                  v-if="!filelist"
                  :auto-upload="false"
                  accept="'.xls,.xlsx,.doc,.docx,.pdf'"
                  action
                  :multiple="false"
                  :before-upload="beforeUpload"
                  :on-exceed="handleExceed"
                  :show-file-list="false"
                  :on-change="handleChansge"
                >
                  <!-- :before-upload="beforeUpload" -->
                  <div class="flex box-row-column box-align-center">
                    <el-icon size="30" color="#01509f"><UploadFilled /></el-icon>
                    <div class="el-upload_tip">点击或者拖拽需要上传的文件</div>
                    <div class="el-upload_tip">文件不超过20M,文件格式:'.xls','.xlsx','.doc','.docx','.pdf'</div>
                  </div>
                </el-upload>
                <!-- <el-button type="text" size="mini" style="font-size: 15px" @click="pdfdetail">查看</el-button> -->
                <div v-if="filelist" class="flex box-align-center" style="width: 100%">
                  <div>
                    <img src="@/assets/image/cf/img31.png" alt="" style="width: 20px; height: 26px" />
                  </div>
                  <div class="zi3 flex-1 ml20">{{ filelist.file_name }}</div>
                  <div class="ml20">
                    <el-button type="text" size="mini" style="font-size: 15px" @click="pdfdetail">查看</el-button>
                    <el-button type="text" size="mini" style="font-size: 15px; color: #ff4345" @click="deleteFile">删除</el-button>
                  </div>
                </div>
              </el-form-item>
              <el-form-item class="" label="合同名称:" prop="task_name">
                <el-input v-model="formadd.task_name" placeholder="请输入合同名称" />
              </el-form-item>
              <el-form-item class="" label="合同类型:" prop="type">
                <el-select v-model="formadd.type" placeholder="请选择合同类型" @change="changeType">
                  <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item class="" label="入职时间:" prop="induction_time" v-if="formadd.typename == '入职协议'">
                <el-date-picker style="width: 100%" v-model="formadd.induction_time" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择入职时间"></el-date-picker>
              </el-form-item>
              <!-- <el-form-item class="" label="入职时间:" prop="time" v-if="formadd.typename == '入职协议'">
                <el-date-picker
                  v-model="formadd.time"
                  type="daterange"
                  range-separator="-"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  placeholder="请选择入职时间"
                ></el-date-picker>
              </el-form-item> -->
              <el-form-item class="" label="劳动合同时间:" prop="labortime" v-if="formadd.typename == '入职协议'">
                <el-date-picker
                  v-model="formadd.labortime"
                  type="daterange"
                  range-separator="-"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  start-placeholder="开始日期"
                  @change="changelaborTime"
                  end-placeholder="结束日期"
                  placeholder="请选择劳动合同时间"
                ></el-date-picker>
              </el-form-item>
              <el-form-item class="" label="劳动合同期:" v-if="formadd.typename == '入职协议'" prop="labor_year">
                <div class="flex justify-content-center">
                  <el-select v-model="formadd.labor_year" placeholder="劳动合同期" style="width: 200px">
                    <el-option key="1" label="无固定期限" value="0" />
                    <el-option key="2" label="6个月" value="1" />
                    <el-option key="3" label="12个月" value="2" />
                    <el-option key="4" label="24个月" value="3" />
                    <el-option key="4" label="36个月" value="4" />
                    <el-option key="4" label="自定义合同期限" value="5" />
                  </el-select>
                  <el-input v-model="formadd.labor_month" placeholder="请输入劳动合同期" v-if="formadd.labor_year == '5'" type="number" style="width: 200px; margin-left: 20px" />
                </div>
              </el-form-item>
              <el-form-item class="" label="劳动试用期:" v-if="formadd.typename == '入职协议'" prop="labortrial_month">
                <el-select v-model="formadd.labortrial_month" placeholder="劳动试用期" style="width: 100%">
                  <el-option key="1" label="无试用期" value="0" />
                  <el-option key="2" label="一个月" value="1" />
                  <el-option key="3" label="二个月" value="2" />
                  <el-option key="4" label="三个月" value="3" />
                  <el-option key="5" label="四个月" value="4" />
                  <el-option key="6" label="五个月" value="5" />
                  <el-option key="7" label="六个月" value="6" />
                </el-select>
              </el-form-item>

              <div class="flex mb20 box-align-center font14 tishired" v-if="isshowts">
                <el-icon color="#ff4345" size="18"><Warning /></el-icon>
                根据劳动合同法规定：劳动合同期限三个月以上不满一年的，试用期不得超过一个月。
              </div>
              <el-form-item class="" label="试用期薪资:" v-if="formadd.typename == '入职协议'" prop="probation_salary">
                <el-input v-model="formadd.probation_salary" placeholder="请输入试用期薪资" />
              </el-form-item>
              <el-form-item class="" label="转正薪资:" v-if="formadd.typename == '入职协议'" prop="obtainment_salary">
                <el-input v-model="formadd.obtainment_salary" placeholder="请输入转正薪资" />
              </el-form-item>

              <!--规章制度签署 -->
              <el-form-item class="" label="生效时间:" prop="effect_time" v-if="formadd.typename == '规章制度签署'">
                <el-date-picker v-model="formadd.effect_time" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择入职时间"></el-date-picker>
              </el-form-item>
              <!--规章制度签署结束 -->
              <!-- 到期续签出现 -->
              <el-form-item class="" label="劳动合同时间:" prop="labortime" v-if="formadd.typename == '到期续签'">
                <el-date-picker
                  v-model="formadd.labortime"
                  type="daterange"
                  range-separator="-"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  start-placeholder="开始日期"
                  @change="changelaborTime"
                  end-placeholder="结束日期"
                  placeholder="请选择劳动合同时间"
                ></el-date-picker>
              </el-form-item>

              <el-form-item class="" label="劳动合同期:" v-if="formadd.typename == '到期续签'">
                <div class="flex justify-content-center">
                  <el-select v-model="formadd.labor_year" placeholder="劳动合同期" style="width: 200px">
                    <el-option key="1" label="无固定期限" value="0" />
                    <el-option key="2" label="6个月" value="1" />
                    <el-option key="3" label="12个月" value="2" />
                    <el-option key="4" label="24个月" value="3" />
                    <el-option key="4" label="36个月" value="4" />
                    <el-option key="4" label="自定义合同期限" value="5" />
                  </el-select>
                  <el-input v-model="formadd.labor_month" placeholder="请输入劳动合同期" v-if="formadd.labor_year == '5'" type="number" style="width: 150px; margin-left: 20px" />
                </div>
              </el-form-item>
              <!-- 到期续签结束 -->
              <!-- 调岗签署出现 -->

              <el-form-item class="" label="调岗时间:" prop="move_jobTime" v-if="formadd.typename == '调岗签署'">
                <el-date-picker v-model="formadd.move_jobTime" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择调岗时间"></el-date-picker>
              </el-form-item>
              <el-form-item class="" label="调岗部门:" v-if="formadd.typename == '调岗签署'">
                <el-select v-model="formadd.move_jobDeptName" placeholder="请选择调岗部门" :popper-append-to-body="false" ref="deptSelect">
                  <el-option :value="selectTree" class="setstyle" disabled>
                    <el-tree :data="depList" :props="defaultProps" ref="tree" :highlight-current="true" @node-click="handleNodeClick" :default-expand-all="false"></el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="" label="调岗职位:" v-if="formadd.typename == '调岗签署'" prop="move_job">
                <el-input v-model="formadd.move_job" placeholder="请输入调岗职位" />
              </el-form-item>
              <!-- 调岗签署出现结束 -->

              <!-- 离职签署出现 -->
              <el-form-item class="" label="离职时间:" prop="departure_time" v-if="formadd.typename == '离职签署'">
                <el-date-picker v-model="formadd.departure_time" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择离职时间"></el-date-picker>
              </el-form-item>
              <!-- 离职签署出现结束 -->

              <div class="flex mt20 box-align-center font14 tishired" v-if="formadd.typename == '入职协议'">
                <el-icon color="#ff4345" size="18"><Warning /></el-icon>
                上述信息如有改动会同步至员工档案
              </div>
            </div>
            <div class="flex flex-v">
              <div class="flex box-align-center mt20">
                <img src="@/assets/image/cf/img30.png" alt="" />
                <div class="zi2">其他信息</div>
              </div>
              <div class="mt20">
                <el-form-item class="" label="签订截止日期:" prop="closing_date">
                  <div class="flex">
                    <el-date-picker v-model="formadd.closing_date" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择入职时间"></el-date-picker>
                    <div class="font14 color333 ml20">如果流程在指定日期过后还没有签订完成，则本次签署自动过期，无法继续签订</div>
                  </div>
                </el-form-item>
              </div>
            </div>
          </el-form>
        </div>
      </div>
    </div>
    <!-- {{ info}} 

  {{ currentComanyInfo }}  -->
    <div class="bottomdiv mt20 flex box-align-center justify-content-end">
      <el-button type="primary" size="mini" color="#01509f" style="font-size: 15px" @click="goNext" class="mr20">下一步</el-button>
    </div>

    <ChooseUser v-model="showDialog" @submit-item="handleSuccess" />
    <ChooseUser1 v-model="showDialog1" @submit-list="handleSuccess1" />
  </div>
</template>
<script setup lang="ts">
  import { onMounted, reactive, ref, computed, nextTick } from "@/TUIKit/adapter-vue";
  import { useRouter, useRoute } from "vue-router";
  import { UserBaseInfo } from "@/api/user";
  import type { TabsPaneContext, ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
  import { contractType, getContractDetailApi, getDepartmentlist, nextStepApi, saveDraftApi } from "@/api/cf";
  import axios from "axios";
  import { useCompanyDataStore } from "@/store/companys";
  import ChooseUser from "@/components/ChooseUser2.vue";
  import ChooseUser1 from "@/components/ChooseUser1.vue";
  import { t } from "@tencentcloud/call-uikit-vue";
  const companyDataStore = useCompanyDataStore();
  const basicCom = ref(null);
  const entryCom = ref(null);
  const jobCom = ref(null);
  const resignCom = ref(null);
  const router = useRouter();
  const route = useRoute();
  const currentComanyInfo = computed(() => companyDataStore.currentComanyInfo);
  const loading = ref(false);
  // const activeName = ref('one')
  const ruleFormRef = ref(null);
  const formadd = ref({
    task_name: "", //合同名称
    typename: route.params.name ? route.params.name : "",
    type: null,
    closing_date: "", //结束日期
    is_signarea: 1, //是否为标志区域
    labor_month: null, //劳动合同期限-自定义
    labor_year: null, //劳动合同期
    labor_start: null, //劳动合同起始时间
    labor_end: null, //劳动合同结束时间
    labor_salary: null, //劳动合同期薪资
    labortime: [],
    effect_time: null, //生效时间
    move_jobTime: null, //调岗时间
    move_jobDeptId: null, //调岗部门
    move_job: null, //调岗职位
    move_jobDeptName: null, //调岗部门名称
    departure_time: null, //离职时间
    probation_salary: "", //试用期薪资
    obtainment_salary: "", //转正薪资
    induction_time: null, //入职时间
    labortrial_month: null, //试用期
    filelist: null,
  });
  const info = ref({
    username: "",
    auth_type: 1,
    auth_name: "",
    create_time: "",
    id_card: "",
    mobile: "",
    legal_person: "",
    establish_time: "",
    legal_person_id: "",
    social_credit_code: "",
    id: 0,
    uid: 0,
    info_id: 0,
    sign_password: "",
  });
  const defaultProps = {
    children: "children",
    label: "name",
  };

  const selectTree = ref([]);
  const showDialog = ref(false);

  const showDialog1 = ref(false);
  const list = ref([]);
  const typeList = ref([]);
  //const detailid = ref(null);

  const detailid = route.params.task_id ? route.params.task_id : "";
  const goBack = () => {
    //router.push({ name: 'employeeList' });
    console.log(detailid.value, "sgssssssssss");
    if (detailid.value) {
      router.back();
    } else {
      ElMessageBox.confirm("是否保存草稿?", "操作提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "ExitConfirmButton",
      })
        .then(() => {
          saveDraft();
        })
        .catch(() => {
          router.back();
        });
    }
  };

  const rules = reactive({
    filelist: [{ required: true, message: "请上传文件", trigger: "blur" }],
    task_name: [{ required: true, message: "请输入合同名称", trigger: "blur" }],
    labortime: [{ required: true, message: "请选择劳动合同时间", trigger: "change" }],
    effect_time: [{ required: true, message: "请选择生效日期", trigger: "change" }],
    move_jobTime: [{ required: true, message: "请选择调岗日期", trigger: "change" }],
    move_job: [{ required: true, message: "请输入调岗职位", trigger: "change" }],
    induction_time: [{ required: true, message: "请选择入职日期", trigger: "change" }],
    probation_salary: [{ required: true, message: "请输入试用期薪资", trigger: "blur" }],
    obtainment_salary: [{ required: true, message: "请输入转正薪资", trigger: "blur" }],
    labor_year: [{ required: true, message: "请选择劳动合同期限", trigger: "change" }],
    type: [{ required: true, message: "请选择合同类型", trigger: "change" }],
    labortrial_month: [{ required: true, message: "请选择试用期", trigger: "change" }],
    labor_month: [{ required: true, message: "请输入自定义合同期限", trigger: "blur" }],
  });

  const changelaborTime = val => {
    formadd.value.labortime = val || []; // 清空时重置为空数组
    formadd.value.labor_start = val[0] ? val[0] : "";

    formadd.value.labor_end = val[1] ? val[1] : "";
    // console.log(formadd.value.labor_start, "formadd.value.labor_start");
    // console.log(formadd.value.labor_end, "formadd.value.labor_end");
  };
  const depList = ref([]);
  const getDepList = async () => {
    await getDepartmentlist("").then(res => {
      depList.value = res.data;
    });
  };

  const isshowts = computed(() => {
    // console.log(formadd.value.labor_year, "formadd.value.typename");
    // console.log(formadd.value.labor_year, "formadd.value.typename");
    // console.log(formadd.value.labortrial_month, "formadd.value.typename");
    if (formadd.value.typename == "入职协议") {
      if (formadd.value.labor_year == 5) {
        if ((formadd.value.labor_month > 3 || formadd.value.labor_month < 12) && formadd.value.labortrial_month > 1) {
          return true;
        } else {
          return false;
        }
      } else if (formadd.value.labor_year < 2 && formadd.value.labor_year && formadd.value.labortrial_month > 1) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  });

  const deleteFile = () => {
    filelist.value = null;
    formadd.value.filelist = null;
    formadd.value.task_name = "";
  };
  const task_id = ref(null);
  const usertype = ref(null);
  const userid = ref(null);
  onMounted(() => {

    usertype.value =route.params.usertype?route.params.usertype : "" 
    userid.value =route.params.userid?route.params.userid : "" 
    contractType().then(res => {
      typeList.value = res.data;
      const typearr = res.data.find(item => item.name === formadd.value.typename);
      if (typearr) {
        formadd.value.type = typearr.id;
      }
    });

    // { main_name: "", join_name: "", join_phone: "", join_type: 0, sign_order: "", join_part: "", seal: 3, userId: "" }
    if (formadd.value.typename == "规章制度签署" || formadd.value.typename == "自定义签署") {
      list.value = [];
    } else {
      list.value = [
        {
          main_name: currentComanyInfo.value.name,
          join_name: currentComanyInfo.value.name,
          join_phone: currentComanyInfo.value.mobile,
          join_type: 2,
          sign_order: "",
          join_part: "",
          seal: 3,
          userId: currentComanyInfo.value.id,
          app_userId: currentComanyInfo.value.user_id,
          yaoqiu: "模板章",
        },
      ];
    }

    // getInfo();
    getDepList();
    const currentDate = new Date();
    const later = new Date(currentDate);
    later.setDate(currentDate.getDate() + 7);
    formadd.value.closing_date = `${later.getFullYear()}-${String(later.getMonth() + 1).padStart(2, "0")}-${String(later.getDate()).padStart(2, "0")}`;
    //   formadd.value.closing_date = now.toLocaleString();
    task_id.value = route.params.task_id ? route.params.task_id : "";

    nextTick(() => {
      if (task_id.value) {
        getContractDetail(task_id.value, route.params.isDraft);
      }
    });
  });

  const findNameById = (data, targetId) => {
    for (const item of data) {
      if (item.id === targetId) {
        return item.name; // 找到目标，返回 name
      }
      if (item.children && item.children.length > 0) {
        const result = findNameById(item.children, targetId); // 递归查找子级
        if (result) return result;
      }
    }
    return null; // 未找到
  };

  const getContractDetail = (id, isDraft) => {
    getContractDetailApi(id, isDraft).then(res => {
      filelist.value = res.data.file;
      formadd.value.filelist = res.data.file;

      if (Number(isDraft) == 1) {
        formadd.value.task_name = res.data.task.task_name;
        formadd.value.type = Number(res.data.task.type);
        formadd.value.closing_date = res.data.task.closing_date;
        formadd.value.is_signarea = 1;
        formadd.value.labor_month = res.data.task.labor_month ? res.data.task.labor_month : null;
        formadd.value.labor_year = res.data.task.labor_year ? res.data.task.labor_year : null;
        formadd.value.labor_start = res.data.task.labor_start ? res.data.task.labor_start : null;

        formadd.value.labor_end = res.data.task.labor_end ? res.data.task.labor_end : null;
        formadd.value.labor_salary = res.data.task.labor_salary ? res.data.task.labor_salary : null;
        formadd.value.labortime = res.data.task.labor_end ? [res.data.task.labor_start, res.data.task.labor_end] : [];
        formadd.value.effect_time = res.data.task.effect_time ? res.data.task.effect_time : null;
        formadd.value.move_jobTime = res.data.task.move_jobTime ? res.data.task.move_jobTime : null;
        formadd.value.move_jobDeptId = res.data.task.move_jobDeptId ? Number(res.data.task.move_jobDeptId) : null;
        formadd.value.move_job = res.data.task.move_job ? res.data.task.move_job : null;
        //formadd.value.move_jobDeptName=res.data.task.move_jobDeptName?res.data.task.move_jobDeptName:null
        formadd.value.departure_time = res.data.task.departure_time ? res.data.task.departure_time : null;
        formadd.value.probation_salary = res.data.task.probation_salary ? res.data.task.probation_salary : "";
        formadd.value.obtainment_salary = res.data.task.obtainment_salary ? res.data.task.obtainment_salary : "";
        formadd.value.induction_time = res.data.task.induction_time ? res.data.task.induction_time : null;
        formadd.value.labortrial_month = res.data.task.labortrial_month ? res.data.task.labortrial_month : null;
        setTimeout(() => {
          if (res.data.task.move_jobDeptId) {
            formadd.value.move_jobDeptName = findNameById(depList.value, formadd.value.move_jobDeptId);
          }
        }, 200);
      } else {
        formadd.value.task_name = res.data.task_name;
        formadd.value.type = Number(res.data.type);
        formadd.value.closing_date = res.data.closing_date;
        formadd.value.is_signarea = 1;
        formadd.value.labor_month = res.data.labor_month ? res.data.labor_month : null;
        formadd.value.labor_year = res.data.labor_year ? res.data.labor_year : null;
        formadd.value.labor_start = res.data.labor_start ? res.data.labor_start : null;

        formadd.value.labor_end = res.data.labor_end ? res.data.labor_end : null;
        formadd.value.labor_salary = res.data.labor_salary ? res.data.labor_salary : null;
        formadd.value.labortime = res.data.labor_end ? [res.data.labor_start, res.data.labor_end] : [];
        formadd.value.effect_time = res.data.effect_time ? res.data.effect_time : null;
        formadd.value.move_jobTime = res.data.move_jobTime ? res.data.move_jobTime : null;
        formadd.value.move_jobDeptId = res.data.move_jobDeptId ? Number(res.data.move_jobDeptId) : null;
        formadd.value.move_job = res.data.move_job ? res.data.move_job : null;
        //formadd.value.move_jobDeptName=res.data.task.move_jobDeptName?res.data.task.move_jobDeptName:null
        formadd.value.departure_time = res.data.departure_time ? res.data.departure_time : null;
        formadd.value.probation_salary = res.data.probation_salary ? res.data.probation_salary : "";
        formadd.value.obtainment_salary = res.data.obtainment_salary ? res.data.obtainment_salary : "";
        formadd.value.induction_time = res.data.induction_time ? res.data.induction_time : null;
        formadd.value.labortrial_month = res.data.labortrial_month ? res.data.labortrial_month : null;
        setTimeout(() => {
          if (res.data.move_jobDeptId) {
            formadd.value.move_jobDeptName = findNameById(depList.value, formadd.value.move_jobDeptId);
          }
        }, 200);
      }
      list.value = res.data.joins;
      console.log(list.value, "list.value");

      //       const formadd = ref({
      //   task_name: "", //合同名称
      //   typename: route.params.name ? route.params.name : "",
      //   type: null,
      //   closing_date: "", //结束日期
      //   is_signarea: 1, //是否为标志区域
      //   labor_month: null, //劳动合同期限-自定义
      //   labor_year: null, //劳动合同期
      //   labor_start: null, //劳动合同起始时间
      //   labor_end: null, //劳动合同结束时间
      //   labor_salary: null, //劳动合同期薪资
      //   labortime: [],
      //   effect_time: null, //生效时间
      //   move_jobTime: null, //调岗时间
      //   move_jobDeptId: null, //调岗部门
      //   move_job: null, //调岗职位
      //   move_jobDeptName: null, //调岗部门名称
      //   departure_time: null, //离职时间
      //   probation_salary: "", //试用期薪资
      //   obtainment_salary: "", //转正薪资
      //   induction_time: null, //入职时间
      //   labortrial_month: null, //试用期
      //   filelist: null,
      // });
    });
  };

  const getInfo = async () => {
    await UserBaseInfo({}).then(res => {
      info.value = res.data.userinfo;
    });
  };

  const radioindex = ref(0);
  const addradio = index => {
    radioindex.value = index;
    showDialog.value = true;
  };

  const handleSuccess = item => {
    list.value[radioindex.value].main_name = "个人";
    list.value[radioindex.value].join_name = item.name;
    list.value[radioindex.value].join_phone = item.mobile;
    list.value[radioindex.value].join_type = 1;
    list.value[radioindex.value].sign_order = "";
    list.value[radioindex.value].join_part = "";
    list.value[radioindex.value].seal = 3;
    list.value[radioindex.value].userId = item.id;
    list.value[radioindex.value].app_userId = item.user_id;
    list.value[radioindex.value].yaoqiu = "模板章";
    showDialog.value = false;
    // console.log(formadd.value.filelist, "Sgsgsggsgsggggg");
  };

  const handleSuccess1 = item => {
    item.forEach(item => {
      const existingItem = list.value.find(listItem => listItem.join_name === item.name && listItem.join_name !== "");

      if (!existingItem) {
        const emptyItemIndex = list.value.findIndex(listItem => listItem.join_name === "");

        if (emptyItemIndex !== -1) {
          // 替换空项
          list.value[emptyItemIndex] = {
            main_name: "个人",
            join_name: item.name,
            join_phone: item.mobile,
            join_type: 1,
            sign_order: "",
            join_part: "",
            seal: 3,
            userId: item.id,
            app_userId: item.user_id,
            yaoqiu: "模板章",
          };
        } else {
          // 推入新项
          list.value.push({
            main_name: "个人",
            join_name: item.name,
            join_phone: item.mobile,
            join_type: 1,
            sign_order: "",
            join_part: "",
            seal: 3,
            userId: item.id,
            app_userId: item.user_id,
            yaoqiu: "模板章",
          });
        }
      }
    });

    showDialog1.value = false;
    // list.value = item;
  };
  const changeType = val => {
    // console.log(val, "sgsgsg");
    const index = typeList.value.findIndex(item => item.id === val);

    if (index !== -1) {
      formadd.value.typename = typeList.value[index].name;
    }
    if (formadd.value.typename == "规章制度签署" || formadd.value.typename == "自定义签署") {
      list.value = [];
    } else {
      list.value = [
        {
          main_name: currentComanyInfo.value.name,
          join_name: currentComanyInfo.value.name,
          join_phone: currentComanyInfo.value.mobile,
          join_type: 2,
          sign_order: "",
          join_part: "",
          seal: 3,
          userId: currentComanyInfo.value.id,
          app_userId: currentComanyInfo.value.user_id,
          yaoqiu: "模板章",
        },
      ];
    }
  };
  const deleteItem = row => {
    const index = list.value.findIndex(item => item.userId === row.userId);
    if (index !== -1) {
      list.value.splice(index, 1);
    }

    /// console.log(formadd.value.filelist, "Sgsgsggsgsggggg");
  };

  const addcompany = () => {
    const aa = {
      main_name: currentComanyInfo.value.name,
      join_name: currentComanyInfo.value.name,
      join_phone: currentComanyInfo.value.mobile,
      join_type: 2,
      sign_order: "",
      join_part: "",
      seal: 3,
      userId: currentComanyInfo.value.id,
      app_userId: currentComanyInfo.value.user_id,
      yaoqiu: "模板章",
    };

    list.value.unshift(aa);
  };
  const add = () => {
    const data = {
      main_name: "个人",
      join_name: "",
      join_phone: "",
      join_type: 1,
      sign_order: "",
      join_part: "",
      seal: 3,
      userId: "",
      app_userId: "",
      yaoqiu: "模板章",
    };

    if (formadd.value.typename == "规章制度签署" || formadd.value.typename == "自定义签署") {
      list.value.push(data);
    } else {
      console.log(list.value.length);
      if (list.value.length === 2) {
        ElMessage.error("最多只能添加1个参与人");
        return false;
      }

      list.value.push(data);
    }
  };

  const beforeUpload = file => {
    const allowedExtensions = [".xls", ".xlsx", ".doc", ".docx", ".pdf"];
    const fileExtension = file.name.slice(file.name.lastIndexOf(".")).toLowerCase();
    if (!allowedExtensions.includes(fileExtension)) {
      //  this.$message.error("请上传 .xls, .xlsx, .doc, .docx 或 .pdf 格式的文件！");
      ElMessage.error("请上传 .xls, .xlsx, .doc, .docx 或 .pdf 格式的文件！");
      return false;
    }
    return true;
  };

  const join_id = ref([]);
  const filelist = ref(null);
  const baseURL = "https://demo-api.niuyuwang.com/";
  const handleChansge = (file, fileList) => {
    let name = file.name;
    let token = localStorage.getItem("token");

    const loading = ElLoading.service({
      lock: true,
      text: "合同上传中,请稍后……",
      background: "rgba(0, 0, 0, 0.3)",
    });

    let formData = new FormData();
    formData.append("contract_file", file.raw);
    formData.append("task_id", task_id.value ? task_id.value : "");
    axios
      .post(baseURL + "hr/manpower/uploadFile", formData, {
        headers: { "Content-Type": "multipart/form-data", token: token },
      })
      .then(response => {
        loading.close();
        if (response.data) {
          // console.log(response.data, "sgsgsgsg");
          filelist.value = response.data.data;
          task_id.value = response.data.data.task_id;
          formadd.value.filelist = response.data.data;
          formadd.value.task_name = response.data.data.file_name.replace(/\.pdf$/, ""); // 去掉末尾的 .pdf
        } else {
          ElMessage({
            message: response.data.msg,
            grouping: true,
            type: "error",
          });
        }
      })
      .catch(err => {
        loading.close();
      });
  };

  function handleExceed(files, fileList) {
    uploadRef.value.clearFiles();

    nextTick(() => {
      uploadRef.value.handleStart(files[0]);
    });
  }

  const pdfdetail = () => {
    //   const link = document.createElement("a");
    //  // link.href = "https://niuyuwang.oss-cn-shanghai.aliyuncs.com/imm-pdf/20251029/新建 DOCX 文档.pdf";
    //   link.target = "_blank";
    //   link.click();
    window.open(filelist.value.pdf_url, "_blank");
  };
  const deptSelect = ref<InstanceType<typeof ElSelect>>();

  const handleNodeClick = (data, self, child) => {
    console.log("data", data);
    // this.labelData = data.label;//展示部分
    // this.valueData = data.id;//传参---id
    formadd.value.move_jobDeptId = data.id;
    formadd.value.move_jobDeptName = data.name;
    // 手动关闭下拉框
    deptSelect.value?.blur();
  };

  const goNext = () => {
    console.log(list.value, "list")
    ruleFormRef.value?.validate(valid => {
      if (valid) {
        // 检查是否有 type === 1
        const hasType1 = list.value.some(item => Number(item.join_type)=== 1);
        if (!hasType1) {
          // console.log("提示：数组中没有 type 为 1 的对象");
          ElMessage({
            message: "请选择参与人",
            grouping: true,
            type: "error",
          });
          return false;
        }
        // 检查是否有 type === 2

        if (formadd.value.typename != "规章制度签署") {
          const hasType2 = list.value.some(item => Number(item.join_type) === 2);
          if (!hasType2) {
            ElMessage({
              message: "请选择企业",
              grouping: true,
              type: "error",
            });
            return false;
          }
        }
        const newObject = Object.entries(formadd.value).reduce((acc, [key, value]) => {
          if (value !== null && value !== undefined && value !== "") {
            acc[key] = value;
          }
          return acc;
        }, {});

        delete newObject.filelist;
        delete newObject.typename;
        delete newObject.labortime;
        newObject.closing_date = newObject.closing_date + " 23:59:59";
        const data = {
          file: filelist.value,
          fileType: 0,
          id: filelist.value.task_id,
          joins: list.value,
          total: filelist.value.total,
          task: newObject,
          type: formadd.value.type,
          // userId:"",
        };

        //  return false

        nextStepApi(data).then(res => {
          ElMessage.success("提交成功");
          // console.log(res.data.image.images[0].task_id, "sgsgw2g2g2g2g2g2g");
          setTimeout(() => {
            router.push({
              name: "SigningCenterDetail",
              params: { id: task_id.value, type: 1,userId:userid.value,usertype:usertype.value },
            });
          }, 1000);
        });
      }
    });
  };

  const saveDraft = () => {
    // console.log("进来了");
    const newObject = Object.entries(formadd.value).reduce((acc, [key, value]) => {
      if (value !== null && value !== undefined && value !== "") {
        acc[key] = value;
      }
      return acc;
    }, {});
    newObject.closing_date = newObject.closing_date + " 23:59:59";
    delete formadd.value.filelist;
    delete formadd.value.typename;
    delete formadd.value.labortime;
    ///  console.log(newObject, "sgsgsg走这儿了");
    // return false
    const data = {
      file: filelist.value ? filelist.value : "",
      fileType: 0,
      id: filelist.value ? filelist.value.task_id : "",
      joins: list.value,
      total: filelist.value ? filelist.value.total : "",
      task: newObject,
      type: formadd.value.type,
      // userId: info.info_id,
    };
    //console.log(data, "走这儿sgsgsg2222222255555555555555555");
    saveDraftApi(data).then(res => {
      ElMessage.success("草稿保存成功");
      // console.log(res.data.image.images[0].task_id, "sgsgw2g2g2g2g2g2g");
      setTimeout(() => {
        router.back();
        //  router.push({ name: "SigningCenterDetail", params: { id:task_id.value, type: 1,userId:route.params.userid?route.params.userid:'',usertype:route.params.usertype?route.params.usertype:''} });
      }, 2000);
    });
  };
</script>

<style lang="scss" scoped>
.company-name {
  font-size: 16px;
  color: #666;

  img {
    margin-left: 5px;
  }
}

.infoBox {
  overflow-y: scroll;
  height: 100%;

  &::-webkit-scrollbar {
    display: none;
  }
}

.setstyle {
  min-height: 200px;
  padding: 0 !important;
  margin: 0;
  overflow: auto;
  cursor: default !important;
}

.el-upload_tip {
  font-size: 15px;
  color: #999;
}

::v-deep .el-upload {
  width: 100% !important;
}

.el-upload-dragger {
  padding: 15px 0 !important;
}

.example-showcase .el-dropdown+.el-dropdown {
  margin-left: 15px;
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: #333;
  display: flex;
  align-items: center;
}

.flexBack {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #333;
  cursor: pointer;
}

.bottomdiv {
  background-color: #fff;
  width: 100%;
  height: 60px;
}

.el-table__header .table-header th {
  font-size: 16px;
  background: #f3f8fb;
  height: 53px;
  color: #6f7070;
  font-weight: normal;
}

.zi1 {
  font-size: 20px;
  color: #01509f;
  // font-family: 黑体;
  font-weight: bold;
}

.zi2 {
  font-size: 17px;
  color: #01509f;
  // font-family: 黑体;
  margin-top: -2px;
  margin-left: 4px;
}

.bottomBox {
  background-color: #fff;
  border-radius: 12px;
  padding: 17px;
  box-sizing: border-box;
  margin-top: 22px;

  .bottomTopBox {
    padding-bottom: 18px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #eaeaea;

    .bottomTitle {
      font-size: 20px;
      color: #333;
      font-weight: bolder;
      flex: 1;
    }

    .bottomRightBox {
      display: flex;
      align-items: center;

      .btnItem1 {
        border-radius: 6px;
        width: 108px;
        height: 36px;
        text-align: center;
        line-height: 30px;
        box-sizing: border-box;
        font-size: 16px;
        // color: #333;
      }

      .btnItem2 {
        border: none;
        border-radius: 6px;
        width: 72px;
        height: 36px;
        text-align: center;
        line-height: 30px;
        box-sizing: border-box;
        font-size: 16px;
      }
    }
  }
}

.avatar-uploader {
  width: 100%;
  text-align: center;
}

.el-upload_tip {
  font-size: 15px;
  color: #999;
}

.el-upload {
  width: 100%;
}

.tishired {
  background-color: #feeeec;
  line-height: 34px;
  font-size: 14px;
  border-radius: 4px;
  padding: 0 10px;
  color: #333;
}
</style>
